﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Newtonsoft.Json;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class MagRoleController : BaseController
    {
        #region 列表

        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            var direction = Request["order[0][dir]"];
            var orderByColumns = new[] {"RoleName", "DisplayName", "Mobile", "UserName", "UserName"};
            var search = Request["search[value]"];
            var pageIndex = start/length + 1;

            var theList = MagRolesBLL.Instance.GetPagingListForPermission(draw, pageIndex, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);

            var jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        #endregion

        #region 添加

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, MagRoles model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            model.Created = DateTime.Now;
            model.CreatedBy = CurrentUser.Id;
            model.Updated = DateTime.Now;
            model.UpdatedBy = CurrentUser.Id;

            var result = MagRolesBLL.Instance.Add(model);

            if (result <= 0) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            return RedirectToAction("List", "MagRole");
        }

        #endregion

        #region 修改

        public ActionResult Update(int id)
        {
            var model = MagRolesBLL.Instance.GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, MagRoles model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            model.Updated = DateTime.Now;
            model.UpdatedBy = CurrentUser.Id;

            var result = MagRolesBLL.Instance.Update(model);

            if (!result) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            return RedirectToAction("List", "MagRole");
        }

        #endregion

        #region 修改角色权限

        public ActionResult UpdatePermission(int id)
        {
            if (id <= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            InitiSet();

            var model = new MagRolePermissionDto
            {
                RoleId = id,
                RoleName = MagRolesBLL.Instance.GetModel(id).Name,
                ListModules = JsonConvert.SerializeObject(MagRoleModulePermissionBLL.Instance.GetModelListByRoleId(id))
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult UpdatePermission(FormCollection collection, MagRolePermissionDto model,
            int[] shopsModule, int[] couponsModule, int[] ordersModule, int[] consumersModule, int[] commodityModule,
            int[] financialModule, int[] payModule, int[] wechatModule, int[] sysConfigModule, int[] commentModule, int [] gfcStatModule)
        {
            var resultClearUp = MagRoleModulePermissionBLL.Instance.ClearSetByRoleIdAndShopId(model.RoleId);
            if (!resultClearUp) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            var modules = new List<int>();
            if(shopsModule != null && shopsModule.Length > 0) modules.AddRange(shopsModule);
            if (couponsModule != null && couponsModule.Length > 0) modules.AddRange(couponsModule);
            if (ordersModule != null && ordersModule.Length > 0) modules.AddRange(ordersModule);
            if (consumersModule != null && consumersModule.Length > 0) modules.AddRange(consumersModule);
            if (commodityModule != null && commodityModule.Length > 0) modules.AddRange(commodityModule);
            if (financialModule != null && financialModule.Length > 0) modules.AddRange(financialModule);
            if (payModule != null && payModule.Length > 0) modules.AddRange(payModule);
            if (wechatModule != null && wechatModule.Length > 0) modules.AddRange(wechatModule);
            if (sysConfigModule != null && sysConfigModule.Length > 0) modules.AddRange(sysConfigModule);
            if (commentModule != null && commentModule.Length > 0) modules.AddRange(commentModule);
            if (gfcStatModule != null && gfcStatModule.Length > 0) modules.AddRange(gfcStatModule);
            if (modules.Count <= 0) return RedirectToAction("List", "MagRole");

            foreach (var moduleId in modules)
            {
                var resultInserting = InsertRolePermissionData(moduleId, model.RoleId);
                if (!resultInserting) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            return RedirectToAction("List", "MagRole");
        }

        #endregion

        #region 删除

        [HttpPost]
        public JsonResult Delete()
        {
            var ids = Request["doIds"];
            var result = MagRolesBLL.Instance.DeleteList(ids);

            return Json(result);
        }

        #endregion

        #region Private Functions 自用函数

        private bool InsertRolePermissionData(int moduleId, int roleId)
        {
            var permissionModel = new MagRoleModulePermission
            {
                Updated = DateTime.Now,
                UpdatedBy = CurrentUser.Id,
                Created = DateTime.Now,
                CreatedBy = CurrentUser.Id,
                ModuleId = moduleId,
                RoleId = roleId,
                IsAllowedToAccess = true
            };

            return MagRoleModulePermissionBLL.Instance.Add(permissionModel) > 0;
        }

        private void InitiSet()
        {
            ViewBag.ShopsModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(2), "Id", "Name");
            ViewBag.CouponsModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(3), "Id", "Name");
            ViewBag.OrdersModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(4), "Id", "Name");
            ViewBag.ConsumersModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(5), "Id", "Name");
            ViewBag.CommodityModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(6), "Id", "Name");
            ViewBag.FinancialModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(7), "Id", "Name");
            ViewBag.PayModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(8), "Id", "Name");
            ViewBag.WechatModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(9), "Id", "Name");
            ViewBag.SysConfigModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(10), "Id", "Name");
            ViewBag.CommentModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(11), "Id", "Name");
            ViewBag.GfcStatModule = new SelectList(MagModulesBLL.Instance.GetModelListByModuleCateId(12), "Id", "Name");
        }

        #endregion
    }
}